"""
系统控制相关路由
"""
from flask import Blueprint, jsonify, request
from services.system_service import system_service
from services.detection_service import detection_service

socketio = None

system_bp = Blueprint('system', __name__, url_prefix='/api/system')

@system_bp.route('/status')
def get_system_status():
    """获取系统状态"""
    return jsonify(system_service.get_status())

# @system_bp.route('/start', methods=['POST'])
# def start_system():
#     """启动系统"""
#     try:
#         if system_service.start_system():
#             # 启动检测循环
#             print(detection_service)
#             if detection_service:
#                 detection_service.start_detection_loop()
            
#             return jsonify({'success': True, 'message': 'System started successfully'})
#         else:
#             return jsonify({'success': False, 'message': 'System is already running'})
#     except Exception as e:
#         return jsonify({'success': False, 'message': str(e)}), 500

# @system_bp.route('/stop', methods=['POST'])
# def stop_system():
#     """停止系统"""
#     try:
#         if system_service.stop_system():
#             return jsonify({'success': True, 'message': 'System stopped successfully'})
#         else:
#             return jsonify({'success': False, 'message': 'System is not running'})
#     except Exception as e:
#         return jsonify({'success': False, 'message': str(e)}), 500 

@system_bp.route('/start', methods=['POST'])
def start_system():
    """启动系统"""
    try:
        if system_service.start_system():
            # 启动检测循环
            print(detection_service)
            if detection_service:
                detection_service.start_detection_loop()
            
            socketio.emit('system_control', {'action': 'start'})
            return jsonify({'success': True, 'message': 'System started successfully'})
        else:
            return jsonify({'success': False, 'message': 'System is already running'})
    except Exception as e:
        return jsonify({'success': False, 'message': str(e)}), 500

@system_bp.route('/stop', methods=['POST'])
def stop_system():
    """停止系统"""
    try:
        if system_service.stop_system():
            socketio.emit('system_control', {'action': 'stop'})
            return jsonify({'success': True, 'message': 'System stopped successfully'})
        else:
            return jsonify({'success': False, 'message': 'System is not running'})
    except Exception as e:
        return jsonify({'success': False, 'message': str(e)}), 500 
    
@system_bp.route('/navigate', methods=['POST'])
def navigate():
    try:
        data = request.get_json(silent=True) or {}
        act = data.get('action')

        if act not in ('home', 'stats'):
            return jsonify({'success': False, 'message': f'Invalid action: {act}'}), 400

        # 确保 socketio 是存在的
        if not socketio:
            return jsonify({'success': False, 'message': 'SocketIO not initialized'}), 500

        socketio.emit('system_control', {'action': f'nav_{act}'})
        return jsonify({'success': True})
    
    except Exception as e:
        import traceback
        traceback.print_exc()
        return jsonify({'success': False, 'message': str(e)}), 500
